package com.sh.data.engine.domain.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.data.engine.domain.common.model.enums.CommonConfigKeyEnum;
import com.sh.data.engine.domain.common.service.ICommonConfigService;
import com.sh.data.engine.repository.dao.common.CommonConfigMapper;
import com.sh.data.engine.repository.dao.common.entity.CommonConfigEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author jingchen.hr
 */
@Service
@Slf4j
public class ICommonConfigServiceImpl extends ServiceImpl<CommonConfigMapper, CommonConfigEntity>
    implements ICommonConfigService {

    @Autowired
    private CommonConfigMapper commonConfigMapper;

    @Override
    public Date getDictionaryMappingTaskLastExeTime() {
        CommonConfigEntity config =
            commonConfigMapper.queryByConfigKey(CommonConfigKeyEnum.DICTIONARY_TASK_TIME_KEY.getKey());
        if (config == null || StringUtils.isBlank(config.getConfigValue())) {
            return null;
        }
        try {
            return new Date(Long.parseLong(config.getConfigValue()));
        } catch (Exception e) {
            log.error("getDictionaryMappingTaskLastExeTime error:", e);
            return null;
        }
    }

    @Override
    public void save(CommonConfigKeyEnum configKeyEnum, String value) {
        CommonConfigEntity config = commonConfigMapper.queryByConfigKey(configKeyEnum.getKey());
        if (config == null) {
            config = new CommonConfigEntity();
            config.setConfigKey(configKeyEnum.getKey());
            config.setConfigValue(value);
            config.setCreateTime(new Date());
            config.setRowState(1);
            commonConfigMapper.insert(config);
        } else {
            CommonConfigEntity update = new CommonConfigEntity();
            update.setId(config.getId());
            update.setConfigValue(value);
            commonConfigMapper.updateById(update);
        }
    }
}
